﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrmContacto.Contracts.Contracts;
using Web.CrmContacto.Code;
using Web.Framework;
using Web.Framework.Translate;
using CrmContacto.Contracts.Enums;
using CrmContacto.Contracts.Contracts.Search;
using CrmContacto.WebApp.Code.InnerClasses;

namespace CrmContacto.WebApp.App
{
    public partial class PlanDeMarketingEdit : BasePage
    {
        public PlanDeMarketing planDeMarketingCurrent
        {
            get
            {
                return (PlanDeMarketing)ViewState["planDeMarketingCurrent"];
            }
            set
            {
                ViewState["planDeMarketingCurrent"] = value;
            }
        }

        protected override void ApplySecurity()
        {
            base.ApplySecurity();

            if (this.planDeMarketingCurrent != null)
            {
                if (this.planDeMarketingCurrent.Id != 0)
                {
                    if ((EstadoPlanDeMarketing)planDeMarketingCurrent.Estado == EstadoPlanDeMarketing.Finalizado ||
                        (EstadoPlanDeMarketing)planDeMarketingCurrent.Estado == EstadoPlanDeMarketing.Cancelado)
                    {
                        this.btnCancelarPlanButton.Visible = false;
                        this.btnFinalizarPlanButton.Visible = false;
                    }

                    SetJavascriptForDeleteRecord(eliminarButton, planDeMarketingCurrent.Nombre);
                    eliminarButton.Visible = true;
                }
                else
                {
                    eliminarButton.Visible = false;
                }
            }
        }

        LinkButton btnCancelarPlanButton = new LinkButton();
        LinkButton btnFinalizarPlanButton = new LinkButton();
        LinkButton eliminarButton = new LinkButton();

        private List<LinkButton> actionButtons = new List<LinkButton>();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            LinkButton guardarButton = new LinkButton();
            guardarButton.ID = "BoCommandGuardar";
            guardarButton.Text = LocalizationProvider.Instance["Bo.Command.Guardar"];
            guardarButton.OnClientClick = "return window.PlanDeMarketingEditObj.ValidateGuardar();";
            guardarButton.Click += new EventHandler(lnkGuardar_Click);
            actionButtons.Add(guardarButton);

            LinkButton volverButton = new LinkButton();
            volverButton.ID = "BoCommandVolver";
            volverButton.CausesValidation = false;
            SetJavascriptForClientClickDirtyChech(volverButton);
            volverButton.Text = LocalizationProvider.Instance["Bo.Command.Volver"];
            volverButton.Click += new EventHandler(volverButton_Click);
            actionButtons.Add(volverButton);

            LinkButton nuevaAccionDeMarketingButton;
            var enumValues = Enum.GetValues(typeof(DiscriminadorAccionDeMarketing));
            foreach (var enumValue in enumValues)
            {

                nuevaAccionDeMarketingButton = new LinkButton();
                nuevaAccionDeMarketingButton.ID = ((DiscriminadorAccionDeMarketing)enumValue).ToString();
                //SetJavascriptForClientClickDirtyChech(nuevaAccionDeMarketingButton);
                nuevaAccionDeMarketingButton.Text = LocalizationProvider.Instance["Bo.PlanDeMarketing.ActionMenu.NuevaAccionDeMarketingGenerica"] + UIHelper.GetEnumDescription(enumValue);
                SetJavascriptForClientClickDirtyChech(nuevaAccionDeMarketingButton);
                nuevaAccionDeMarketingButton.CausesValidation = false;
                //nuevaAccionDeMarketingButton.OnClientClick = "location.href = '" + Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingEdit + string.Format("?DiscriminadorId={0}&PlanDeMarketingId={1}'", (int)enumValue, planDeMarketingCurrent.Id);
                actionButtons.Add(nuevaAccionDeMarketingButton);
            }

            //nuevaAccionDeMarketingButton.Text = LocalizationProvider.Instance["Bo.PlanDeMarketing.ActionMenu.NuevaAccionDeMarketing"];
            //nuevaAccionDeMarketingButton.Click += new EventHandler(nuevaAccionDeMarketingButton_Click);
            //actionButtons.Add(nuevaAccionDeMarketingButton);

            LinkButton btnBuscarAccionesButton = new LinkButton();
            btnBuscarAccionesButton.ID = "BoCommandBuscarAccionesDeMarketing";
            btnBuscarAccionesButton.CausesValidation = false;
            SetJavascriptForClientClickDirtyChech(btnBuscarAccionesButton);
            btnBuscarAccionesButton.Text = LocalizationProvider.Instance["Bo.Command.BuscarAccionesDeMarketing"];
            btnBuscarAccionesButton.Click += new EventHandler(btnBuscarAccionesButton_Click);
            actionButtons.Add(btnBuscarAccionesButton);

            btnCancelarPlanButton.ID = "BoCommandCancelar";
            btnCancelarPlanButton.CausesValidation = false;
            SetJavascriptForClientClickDirtyChech(btnCancelarPlanButton);
            btnCancelarPlanButton.Click += new EventHandler(CancelarButton_Click);
            btnCancelarPlanButton.Text = LocalizationProvider.Instance["Bo.Command.CambiarEstado.Cancelado"];
            actionButtons.Add(btnCancelarPlanButton);

            btnFinalizarPlanButton.ID = "BoCommandFinalizar";
            SetJavascriptForClientClickDirtyChech(btnFinalizarPlanButton);
            btnFinalizarPlanButton.CausesValidation = false;
            btnFinalizarPlanButton.Click += new EventHandler(FinalizarButton_Click);
            btnFinalizarPlanButton.Text = LocalizationProvider.Instance["Bo.Command.CambiarEstado.Finalizado"];
            actionButtons.Add(btnFinalizarPlanButton);

            eliminarButton.ID = "BoCommandEliminar";
            eliminarButton.CausesValidation = false;
            eliminarButton.Text = LocalizationProvider.Instance["Bo.Command.Eliminar"];
            eliminarButton.Click += new EventHandler(eliminarButton_Click);
            actionButtons.Add(eliminarButton);

            base.LoadContextActions(actionButtons);

            // Fix de una locura que se pierden los eventos

            this.lnkGuardar.Click += new EventHandler(lnkGuardar2_Click);
        }

        private void eliminarButton_Click(object sender, EventArgs e)
        {
            try
            {
                WebServiceHelper.EliminarPlanDeMarketing(planDeMarketingCurrent.Id);
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlPlanDeMarketingList + string.Format("?{0}=1", MiscClass.QueryShowDeleted), true);
                //NuevoPlanDeMarketing();
                //Bind();
                //this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Message.RegistroEliminado"], WebMessageType.Notification);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void CancelarButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (planDeMarketingCurrent.Id != 0 && planDeMarketingCurrent.Estado.HasValue)
                {
                    WebServiceHelper.CambiarEstadoAPlanDeMarketing(planDeMarketingCurrent.Id, (int)EstadoPlanDeMarketing.Cancelado);
                    planDeMarketingCurrent.Estado = (int)EstadoPlanDeMarketing.Cancelado;
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void FinalizarButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (planDeMarketingCurrent.Id != 0 && planDeMarketingCurrent.Estado.HasValue)
                {
                    WebServiceHelper.CambiarEstadoAPlanDeMarketing(planDeMarketingCurrent.Id, (int)EstadoPlanDeMarketing.Finalizado);
                    planDeMarketingCurrent.Estado = (int)EstadoPlanDeMarketing.Finalizado;
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {                
                if (!this.IsPostBack)
                {
                    if (this.Request.QueryString["Id"] == null)
                    {
                        NuevoPlanDeMarketing();
                    }
                    else
                    {
                        PlanDeMarketingSearch search = new PlanDeMarketingSearch()
                        {
                            Id = Convert.ToInt32(this.Request.QueryString["Id"]),
                            LoadAccionesDeMarketing = true,
                            EmpresaId = BasePage.CompanyId
                        };

                        planDeMarketingCurrent = WebServiceHelper.GetPlanesDeMarketing(search).First();
                    }

                    LoadCbos();

                    Bind();
                }

                LinkButton nuevaAccionDeMarketingButton;
                var enumValues = Enum.GetValues(typeof(DiscriminadorAccionDeMarketing));
                foreach (var enumValue in enumValues)
                {
                    nuevaAccionDeMarketingButton = actionButtons.Where(p => p.ID == ((DiscriminadorAccionDeMarketing)enumValue).ToString()).Single();

                    if (((DiscriminadorAccionDeMarketing)enumValue) == DiscriminadorAccionDeMarketing.Comunicacion)
                    {
                        // tengo que agregar que elija el tipo de comunicación a agregar, para eso muestro un popup
                        string clickStr = "window.PlanDeMarketingEditObj.ShowPickTipoComunicacion('" + Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingSwap + string.Format("?DiscriminadorId={0}&PlanDeMarketingId={1}'); return false;", (int)enumValue, planDeMarketingCurrent.Id);
                        nuevaAccionDeMarketingButton.OnClientClick = clickStr;
                    }
                    else
                    {
                        nuevaAccionDeMarketingButton.OnClientClick = "location.href = '" + Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingSwap + string.Format("?DiscriminadorId={0}&PlanDeMarketingId={1}'; return false;", (int)enumValue, planDeMarketingCurrent.Id);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void NuevoPlanDeMarketing()
        {
            planDeMarketingCurrent = new PlanDeMarketing();
            planDeMarketingCurrent.Estado = (int)EstadoPlanDeMarketing.NoIniciado;
        }

        private void LoadCbos()
        {
            //UIHelper.LoadEstados<EstadoPlanDeMarketing>(this.cboEstado, LocalizationProvider.Instance["DropDown.SinEspecificar"]);

            var CrmContactoSrv = ServiceFactory.ServiceFactory.Instance.GetCrmContactoAdminService();
            TipoAccionDeMarketingComunicacionSearch search = new TipoAccionDeMarketingComunicacionSearch();
            search.EmpresaId = BasePage.CompanyId;
            var list = CrmContactoSrv.GetMarketingComunicacionTipo(search);
            UIHelper.LoadCbo(list, cboTipoAccionComunicacion, string.Empty);            
        }

        private void Bind()
        {
            if (planDeMarketingCurrent.AccionDeMarketingList.Count == 0)
            {
                pnlWrapAccionesDeMarketing.Visible = false;
            }

            this.txtNombre.Text = planDeMarketingCurrent.Nombre;
            this.txtDescripcion.Text = planDeMarketingCurrent.Descripcion;
            this.txtResposable.Text = planDeMarketingCurrent.Responsable;

            if(planDeMarketingCurrent.VigenciaDesde.HasValue)
            {
                this.txtVigenciaDesde.Text = planDeMarketingCurrent.VigenciaDesde.Value.ToString("dd/MM/yyyy");
            }

            if (planDeMarketingCurrent.VigenciaHasta.HasValue)
            {
                this.txtVigenciaHasta.Text = planDeMarketingCurrent.VigenciaHasta.Value.ToString("dd/MM/yyyy");
            }

            if (planDeMarketingCurrent.Estado.HasValue)
            {
                //this.cboEstado.SelectedValue = Convert.ToString(planDeMarketingCurrent.Estado.Value);
                this.lblEstado.Text = UIHelper.GetEnumDescription((EstadoPlanDeMarketing)planDeMarketingCurrent.Estado.Value);
            }            

            BindAccionesDeMarketing();
        }

        private void BindAccionesDeMarketing()
        {
            this.GridAccionesDeMarketing.DataSource = planDeMarketingCurrent.AccionDeMarketingList;
            this.GridAccionesDeMarketing.DataBind();
        }

        private void SetData()
        {
            planDeMarketingCurrent.Nombre = this.txtNombre.Text;
            planDeMarketingCurrent.Descripcion = this.txtDescripcion.Text;
            planDeMarketingCurrent.Responsable = this.txtResposable.Text;
            //planDeMarketingCurrent.Estado = UIHelper.GetIntFromInputCbo(this.cboEstado);
            planDeMarketingCurrent.EmpresaId = BasePage.CompanyId;
            planDeMarketingCurrent.VigenciaDesde = UIHelper.GetDateTimeFromInputText(this.txtVigenciaDesde.Text);
            planDeMarketingCurrent.VigenciaHasta = UIHelper.GetDateTimeFromInputText(this.txtVigenciaHasta.Text);
        }

        private void Save()
        {

            bool esNuevo = planDeMarketingCurrent.Id == 0;
            planDeMarketingCurrent = WebServiceHelper.SavePlanDeMarketing(planDeMarketingCurrent);

            if (esNuevo)
            {
                LinkButton nuevaAccionDeMarketingButton;
                var enumValues = Enum.GetValues(typeof(DiscriminadorAccionDeMarketing));
                foreach (var enumValue in enumValues)
                {
                    nuevaAccionDeMarketingButton = actionButtons.Where(p => p.ID == ((DiscriminadorAccionDeMarketing)enumValue).ToString()).Single();
                    nuevaAccionDeMarketingButton.OnClientClick = "location.href = '" + Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingSwap + string.Format("?DiscriminadorId={0}&PlanDeMarketingId={1}'; return false;", (int)enumValue, planDeMarketingCurrent.Id);
                }
            }
        }

        protected void GridAccionesDeMarketing_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    AccionDeMarketing accionDeMarketing = (AccionDeMarketing)e.Row.DataItem;

                    e.Row.Cells[0].Attributes.Add("title", "Editar");
                    e.Row.Cells[1].Attributes.Add("title", "Eliminar");

                    ImageButton btnEditarCtrl = (ImageButton)e.Row.FindControl("btnEditar");
                    SetJavascriptForClientClickDirtyChech(btnEditarCtrl);

                    ImageButton btnEliminarCtrl = (ImageButton)e.Row.FindControl("btnEliminar");
                    SetJavascriptForDeleteRecord(btnEliminarCtrl, accionDeMarketing.Nombre);                      

                    e.Row.Cells[6].Text = UIHelper.GetEnumDescription((DiscriminadorAccionDeMarketing)accionDeMarketing.Discriminador);
                    e.Row.Cells[7].Text = UIHelper.GetEnumDescription((EstadoPlanDeMarketing)accionDeMarketing.Estado);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridAccionesDeMarketing_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int accionDeMarketingId = Convert.ToInt32(this.GridAccionesDeMarketing.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingSwap + "?Id={0}", accionDeMarketingId), true);
                }
                else if (e.CommandName == "eliminar")
                {
                    int accionDeMarketingId = Convert.ToInt32(this.GridAccionesDeMarketing.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    WebServiceHelper.EliminarAccionDeMarketing(accionDeMarketingId);
                    var camp = planDeMarketingCurrent.AccionDeMarketingList.Where(i => i.Id == accionDeMarketingId).Single();
                    planDeMarketingCurrent.AccionDeMarketingList.Remove(camp);
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridAccionesDeMarketing_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.GridAccionesDeMarketing.PageIndex = e.NewPageIndex;
                BindAccionesDeMarketing();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void lnkGuardar_Click(object sender, EventArgs e)
        {
            lnkGuardarMethod();
        }

        private void lnkGuardar2_Click(object sender, EventArgs e)
        {
            lnkGuardarMethod();
        }

        private void lnkGuardarMethod()
        {
            try
            {
                SetData();
                Save();
                Bind();
                this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Messages.MensajeSaveExitoso"], WebMessageType.Notification);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void volverButton_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlPlanDeMarketingList, true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void btnBuscarAccionesButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.planDeMarketingCurrent.Id != 0)
                {                                        
                    string cleanURL = this.Request.Url.AbsoluteUri.Replace(this.Request.Url.Query, string.Empty);
                    base.NavigationContext.UrlToGoBack = cleanURL;
                    Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingList + string.Format("?planDeMarketingId={0}", this.planDeMarketingCurrent.Id), true);
                }                
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void nuevaAccionDeMarketingButton_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingSwap + string.Format("?PlanDeMarketingId={0}", planDeMarketingCurrent.Id), true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}